package com.ds.api.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.ds.api.dao.DSAdvertMapper;
import com.ds.api.model.DSAdvert;

@Controller  
@RequestMapping("/advert")  
public class AdvertController {
    
    @Autowired
    private DSAdvertMapper mapper;
    
    @RequestMapping(value="/list")  
    private String fildUpload( 
            HttpServletRequest request,@RequestParam Map<String,Object> map,Model model)throws Exception{  
     
        //获得物理路径webapp所在路径  
        List<DSAdvert> list=mapper.query(map);
        model.addAttribute("list", list);
        return "advert";
      
    } 
    
    @RequestMapping(value="/upload",method=RequestMethod.POST)  
    private String fildUpload(@RequestParam(value="file",required=false) MultipartFile[] file,  
            HttpServletRequest request)throws Exception{  

        //获得物理路径webapp所在路径  
//        String pathRoot = request.getSession().getServletContext().getRealPath("");  
        
        String path="/opt/img/image/";
//        String path="D:/file/";
        for (MultipartFile mf : file) {  
            if(!mf.isEmpty()){  
                //生成uuid作为文件名称  
                //获得文件类型（可以判断如果不是图片，禁止上传）  
//                String contentType=mf.getContentType();  
                //获得文件后缀名称  
                String imageName=new Date().getTime()+".png";
                mf.transferTo(new File(path+imageName));  
                DSAdvert dsAdvert=new DSAdvert();
                dsAdvert.setUrl(imageName);
                mapper.insert(dsAdvert);
            }  
        }  
        return "redirect:/advert/list";
    }  
}
